package com.pomr.service.equipmentstorage.impl;


import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.equipmentstorage.EquipmentStorageDao;
import com.pomr.model.equipmentstorage.EquipmentInStorage;
import com.pomr.model.equipmentstorage.EquipmentStorage;
import com.pomr.model.equipmentstorage.EquipmentStorageDetail;
import com.pomr.model.menu.EquipmentCondition;
import com.pomr.model.menu.EquipmentStatus;
import com.pomr.model.synthesize.Manufacturer;
import com.pomr.model.sys.Agency;
import com.pomr.service.equipmentstorage.EquipmentStorageService;
import com.pomr.util.page.Page;
@Service
public class EquipmentStorageServiceImpl implements EquipmentStorageService {
	@Autowired
	@Qualifier("equipmentStorageDaoImpl")
	private EquipmentStorageDao equipmentStorageDao;

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean inStorage(EquipmentInStorage storage) throws Exception {
		//入库记录-只是保存，需要审核后才能写入库存
		return equipmentStorageDao.add(storage);
	}

	
	@Override
	public Page<List<EquipmentInStorage>> searchEquipmentInStorages(String equipmentid, String agencyid,
			String manufacturerid, String status, String time1, String time2, String page, String limit) throws Exception {
		String hql = "from Agency where id = "+agencyid;
		List<Agency> a = equipmentStorageDao.findByHql(hql);
		StringBuilder sb = new StringBuilder();
		sb.append("from EquipmentInStorage ");
		int i=0;
		if(equipmentid!=null && !equipmentid.equals("")){
			i++;
			sb.append("where equipment.id = "+equipmentid+" ");
		}
		if(agencyid!=null && !agencyid.equals("")){
			
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			if(status!=null && status.equals("0")){//包含下属机构
				sb.append("agency.id in (select a1.id from Agency a1 where a1.identifier like '"+a.get(0).getIdentifier()+"%') ");
			}else{
				sb.append("agency.id = "+agencyid+" ");
			}
			i++;
		}
		if(manufacturerid!=null && !manufacturerid.equals("")){
			
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("manufacturer.id = "+manufacturerid+" ");
			i++;
		}
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> parammap = new HashMap<String, Object>();
		boolean istime = false;
		if(time1!=null && !time1.equals("")){
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("inTime >= :startDate ");
			parammap.put("startDate", sf.parse(time1));
			i++;
			istime = true;
		}
		if(time2!=null && !time2.equals("")){
			if(i>0){
				sb.append("and ");
			}else{
				sb.append("where ");
			}
			sb.append("inTime <= :endDate ");
			parammap.put("endDate", sf.parse(time2));
			i++;
			istime = true;
		}
		sb.append(" order by inTime desc" );
		String hqlStr = sb.toString();
		Page<List<EquipmentInStorage>> p = new Page<List<EquipmentInStorage>>();
		p.setCunrrentPage(Integer.valueOf(page));
		p.setPageSize(Integer.valueOf(limit));
		if(!istime){
			return equipmentStorageDao.showPage(hqlStr, "select count(1) "+hqlStr, p);
		}
		return equipmentStorageDao.showPageParam(hqlStr, "select count(1) "+hqlStr, p,parammap);
	}


	@Override
	public EquipmentInStorage searchEquipmentInStorageById(EquipmentInStorage instor) throws Exception {
		String hql = "from EquipmentInStorage e left join fetch e.equipment left join fetch e.manufacturer "
				+ "left join fetch e.agency left join fetch e.inUser left join fetch e.createUser where e.id="+instor.getId();
		List<EquipmentInStorage> es = equipmentStorageDao.findByHql(hql);
		if(es==null || es.size()<=0){
			return null;
		}
		return es.get(0);
	}


	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteEquipmentInStorageById(String[] ids,String del) throws Exception {
		EquipmentInStorage instor = null;
		for(String id:ids){
			// TODO 只有未经审核的入库记录可以删除
			instor = equipmentStorageDao.getById(EquipmentInStorage.class, Integer.valueOf(id));
			if(instor.getState()!=null && instor.getState().equals("1")){//入库记录已经审核 不能删除
				throw new Exception("库存记录已经审核，无法删除，id:"+id);
			}
			if(equipmentStorageDao.removeEntity(instor)){//删除成功-更改库存记录-删除详细信息
			}else{
				throw new Exception("入库记录删除失败");
			}
		}
		
		return true;
	}


	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean reviewEquipmentInStorageById(String[] ids) throws Exception {
		EquipmentInStorage instor = null;
		for(String id:ids){
			// TODO 只有未经审核的入库记录可以删除
			instor = equipmentStorageDao.getById(EquipmentInStorage.class, Integer.valueOf(id));
			if(instor.getState()!=null && instor.getState().equals("1")){//入库记录已经审核 不能删除
				throw new Exception("库存记录已经审核，无法在进行审核，id:"+id);
			}
			instor.setState("1");
			String eshql = "update EquipmentInStorage set state='1' where id="+id;
			if(equipmentStorageDao.editHql(eshql)){
			//	库存主表（更新库存等）
				EquipmentStorage estorage = new EquipmentStorage();
				estorage.setAgency(instor.getAgency());
				estorage.setEquipment(instor.getEquipment());
				estorage.setManufacturer(instor.getManufacturer());
				String hql = "from EquipmentStorage where equipment.id="+estorage.getEquipment().getId()+" and manufacturer.id="
						+estorage.getManufacturer().getId()+" and agency.id="+estorage.getAgency().getId();
				List<EquipmentStorage> es = equipmentStorageDao.findByHql(hql);
				Integer estorageid = null;
				if(es==null || es.size()<=0){//不存在库存 --保存
					estorage.setStockNumber(instor.getNumber());
					if((estorageid = equipmentStorageDao.addNumKey(estorage))==null){
						throw new Exception("保存库存记录失败");
					}
				}else{//已存在库存--更新库存数据
					EquipmentStorage estor = es.get(0);
					estor.setStockNumber(estor.getStockNumber()+instor.getNumber());
					if(!equipmentStorageDao.editEntity(estor)){
						throw new Exception("更新库存记录失败");
					}
					estorageid = estor.getId();
				}
				//库存明细表
				String endsn = instor.getEndSN();
				String startsn = instor.getStartSN();
				String imeiendsn = instor.getImeiendSN();
				String imeistartsn = instor.getImeistartSN();
				boolean isLX = true;
				if(imeiendsn==null || "".equals(imeiendsn)){//非连续IMEI
					isLX = false;
				}
				
				if(endsn==null || "".equals(endsn)){//非连续SN码
					String[] sns = startsn.split(",");
					EquipmentStorage stor = new EquipmentStorage();
					stor.setId(estorageid);
					for(int i=0; i<sns.length; i++){
						System.out.println("--------");
						EquipmentStorageDetail detail = new EquipmentStorageDetail();//新建对象 不然会报错
						EquipmentStatus status = new EquipmentStatus();
						EquipmentCondition con = new EquipmentCondition();
						detail.setEquipmentStorage(stor);
						detail.setId(null);
						detail.setsN(instor.getPrefix()+sns[i]+instor.getSuffix());
						if(imeistartsn!=null && !"".equals(imeistartsn.trim())){//存在imei
							int ilen = imeistartsn.length();//编码长度
							if(isLX){//连续
								long stratimei =  Long.parseLong(imeistartsn.trim());
								String imei = "00000000000000000000000000"+(stratimei+i);
								imei = imei.substring(imei.length()-ilen);
								detail.setImei(instor.getImeiprefix()+imei+instor.getImeisuffix());
							}else{//非连续
								String[] imeis = imeistartsn.split(",");
								System.out.println(imeis[i]);
								if(imeis.length<=(i+1)){
									detail.setImei(instor.getImeiprefix()+imeis[i]+instor.getImeisuffix());
								}
							}
						}
						status.setId(1);
						detail.setEquipmentStatus(status);
						con.setId(1);
						detail.setEquipmentCon(con);
						if(!equipmentStorageDao.add(detail)){
							throw new Exception("更新库存记录明细失败");
						}
					}
				}else{//连续SN码
					EquipmentStorage stor = new EquipmentStorage();
					stor.setId(estorageid);
					int len = startsn.length();//编码长度
					long strat =  Long.parseLong(startsn);
					long end =  Long.parseLong(endsn);
					int j = 0;
					for(long i=strat;i<=end;i++){
						EquipmentStorageDetail detail = new EquipmentStorageDetail();//新建对象 不然会报错
						EquipmentStatus status = new EquipmentStatus();
						EquipmentCondition con = new EquipmentCondition();
						detail.setEquipmentStorage(stor);
						detail.setId(null);
						//编码补足0
						String sns = "00000000000000000000000000"+i;
						sns = sns.substring(sns.length()-len);
						detail.setsN(instor.getPrefix()+sns+instor.getSuffix());
						if(imeistartsn!=null && !"".equals(imeistartsn.trim())){//存在imei
							int ilen = imeistartsn.length();//编码长度
							if(isLX){//连续
								long stratimei =  Long.parseLong(imeistartsn.trim());
								String imei = "00000000000000000000000000"+(stratimei+j);
								imei = imei.substring(imei.length()-ilen);
								detail.setImei(instor.getImeiprefix()+imei+instor.getImeisuffix());
							}else{//非连续
								String[] imeis = imeistartsn.split(",");
								if(imeis.length<=(i+1)){
									detail.setImei(instor.getImeiprefix()+imeis[j]+instor.getImeisuffix());
								}
							}
						}
						status.setId(1);
						detail.setEquipmentStatus(status);
						con.setId(1);
						detail.setEquipmentCon(con);
						j++;
						if(!equipmentStorageDao.add(detail)){
							throw new Exception("更新库存记录明细失败");
						}
					}
				}
			}else{
				throw new Exception("入库记录审核失败，id"+id);
			}
		}
		return true;
	}
	
	

}
